//
//  LSLock.swift
//  LSTools
//
//  Created by zrf on 2021/7/6.
//

import Foundation

public struct LSLock{
    static var lock: os_unfair_lock = os_unfair_lock()
    public static var smp =  DispatchSemaphore(value: 1)
    
    //互斥信号量，同一时间只能执行一个
    //MARK: - os_unfair_lock
    static public func unfairLock(_ closure:()->Void){
        //加锁
        os_unfair_lock_lock(&lock)
        defer {
            os_unfair_lock_unlock(&lock)
        }
        closure()
    }
    
    //MARK: - 信号量
    
    /// 信号量实现线程控制
    /// - Parameters:
    ///   - sema: 允许线程同步数， 默认为DispatchSemaphore(value: 1),使用默认时功能与上面类似
    ///   - closure: 真正处理的事物
    public static func semaphoreLock(_ sema:DispatchSemaphore = smp, _ closure:()->Void){
        sema.wait()
        defer {
            sema.signal()
        }
        closure()
    }
}
